package vn.allmobile.ambnews.customview;


import java.io.File;

import vn.allmobile.ambnews.activities.detail.DetailActivity;
import vn.allmobile.ambnews.network.NetworkChangeReceiver;
import vn.allmobile.ambnews.utils.Log;

import android.content.Context;
import android.graphics.Canvas;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;

public class WebviewDetail extends WebView {
	DetailActivity _activity = null;
	Context _context;
	GestureDetector gd;
	public static int _currentPage = 0;
	WebviewDetail _webview;
	Boolean is_sync = false;
	//GestureDetector gestureDetector = new GestureDetector(new MyGestureDetector());
	private GestureDetector gestureDetector;
	@SuppressWarnings("deprecation")
	public WebviewDetail(Context context) {
		super(context);	
		// TODO Auto-generated constructor stub		 	
		// this.addJavascriptInterface(new WebAppInterface(context), "SLBridge");
		_context = context;
		_webview = this;
		this.gestureDetector = new GestureDetector(new CustomeGestureDetector());
		//gd = new GestureDetector(_context, sogl);
		//gd = new GestureDetector(sogl);
	}


	@SuppressWarnings("deprecation")
	public WebviewDetail(Context context, AttributeSet attrs) {
		super(context, attrs);
		_context = context;
		_webview = this;
		//gd = new GestureDetector(_context, sogl);
		// TODO Auto-generated constructor stub
		this.gestureDetector = new GestureDetector(new CustomeGestureDetector());
	}

	@SuppressWarnings("deprecation")
	public WebviewDetail(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		_context = context;
		_webview = this;
		//gd = new GestureDetector(_context, sogl);
		// TODO Auto-generated constructor stub
		is_sync = false;
		this.gestureDetector = new GestureDetector(new CustomeGestureDetector());
	}
	
	
	public void setIsSync(boolean sync)
	{
		is_sync = sync;
		
	}
	public void init()
	{

		 WebSettings webSettings = this.getSettings();
		 webSettings.setJavaScriptEnabled(true);
		 webSettings.setDatabaseEnabled(true);
		 webSettings.setDatabasePath("/data/data/" + _context.getPackageName() + "/databases/");
		 webSettings.setDomStorageEnabled(true);
		 webSettings.setAppCacheEnabled( true );
		 webSettings.setBuiltInZoomControls(false);
		 webSettings.setSupportZoom(false);	        
	     webSettings.setAllowFileAccess(true);
	     webSettings.setDomStorageEnabled(true);	       
		 webSettings.setRenderPriority(RenderPriority.HIGH);
		
		 webSettings.setDefaultTextEncodingName("UTF-8");
		 webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
		 
		 webSettings.setUseWideViewPort(true);
		 this.setHorizontalScrollBarEnabled(false);
		 this.setVerticalScrollBarEnabled(false);
	     
	     
	     this.setLongClickable(false);
	     this.setOnLongClickListener(new OnLongClickListener() {
	    	    @Override
	    	    public boolean onLongClick(View v) {
	    	        return true;
	    	    }
	    	});
		 //webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
		 if (Environment.getExternalStorageState().equals("mounted"))
		 {
			 Log.v("mounted");
			 String cachePath= "";
		    for (File localFile = new File(Environment.getExternalStorageDirectory(), "Android/data/"+_context.getPackageName()+"/webcache"); ;localFile = _context.getCacheDir())
		    {
		      if (!localFile.exists())
		      {
		    	  localFile.mkdirs();
		      }
		       cachePath = localFile.getAbsolutePath();
		       break;
		    }
		    Log.v("cachePath:"  +cachePath);
			 webSettings.setAppCachePath(cachePath);
			// webSettings.setAppCacheMaxSize(10 * 1024 * 1024 );
		 }	
		 if(is_sync)
		 {
			 this.setWebViewClient(new WebviewDetailClientForCache());
		 }
		 else
		 {
			 this.setWebViewClient(new WebviewDetailClient(_context,_activity)); 
		 }
		 this.setWebChromeClient(new WebviewDetailChromeClient(_context));
		 //
		// 
		 	
		// this.setScrollContainer(false);
		 
	}
	
	
	
	
	
	@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        invalidate();
    }




	/**
	 * @param _activity the _activity to set
	 */
	public void set_activity(DetailActivity _activity) {
		this._activity = _activity;
	}
	
		
		
	 	
	@Override
    public boolean onTouchEvent(MotionEvent event) {
		try{
			if( _activity._isLoaded == 1)
			{
				return (gestureDetector.onTouchEvent(event) 
				        || super.onTouchEvent(event));			    		
			}
			return true;
		}catch(Exception e){
			return true;
		}
		
					   
    }

  private class CustomeGestureDetector extends SimpleOnGestureListener {    
	  
	  	
	    /* (non-Javadoc)
	 * @see android.view.GestureDetector.SimpleOnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float)
	 */
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		
		if(e1.getPointerCount() > 1 || e2.getPointerCount() > 1) return false;
		
		else if(e1.getY() - e2.getY() > 40 && Math.abs(velocityY) > 100)
		{
			if(DetailActivity._currentPage < DetailActivity._totalPage - 1 )
        	{
        		Log.v("_activity._currentPage: " +DetailActivity._currentPage);
        		Log.v(" _activity._screenHeight:"  + DetailActivity._screenHeight);
        		
        		DetailActivity._currentPage =  DetailActivity._currentPage + 1 ;
            	//int scrollTo = _activity._currentPage * _activity._screenHeight;
            	//Log.v("scrollTo:" + scrollTo);
            	String scrollTo  = "var page = $('.page').eq("+ (DetailActivity._currentPage) +").position().top;$('html, body').stop().animate({scrollTop: page}, 300);";
            	WebviewDetail.this.loadUrl("javascript:"+scrollTo);
            	//WebviewDetail.this.loadUrl("javascript:window.scrollTo(0,"+scrollTo+")");
            	return true;
        	}
		}
		else if(  e2.getY() - e1.getY() > 40 && Math.abs(velocityY) > 100)
		{
			if(DetailActivity._currentPage >= 1)
        	{
        		DetailActivity._currentPage -- ;
        		Log.v("_activity._currentPage: " +DetailActivity._currentPage);
        		Log.v(" _activity._screenHeight:"  + DetailActivity._screenHeight);
        	
            	//int scrollTo = _activity._currentPage * _activity._screenHeight;
            	//Log.v("scrollTo:" + scrollTo);
            	String scrollTo  = "var page = $('.page').eq("+ (DetailActivity._currentPage) +").position().top;$('html, body').stop().animate({scrollTop: page}, 300);";
            	WebviewDetail.this.loadUrl("javascript:"+scrollTo);
            	return true;
        	}
		}
		
		else if((e1.getX() - e2.getX() > 40 && Math.abs(velocityX) > 100)) {
            
        	if(DetailActivity._currentPage < DetailActivity._totalPage - 1 )
        	{
        		Log.v("_activity._currentPage: " +DetailActivity._currentPage);
        		Log.v(" _activity._screenHeight:"  + DetailActivity._screenHeight);
        		
        		DetailActivity._currentPage =  DetailActivity._currentPage + 1 ;
            	//int scrollTo = _activity._currentPage * _activity._screenHeight;
            	//Log.v("scrollTo:" + scrollTo);
        		String scrollTo  = "var page = $('.page').eq("+ (DetailActivity._currentPage) +").position().top;$('html, body').stop().animate({scrollTop: page}, 300);";
            	WebviewDetail.this.loadUrl("javascript:"+scrollTo);
            	return true;
        	}
        	
        } //left to right swipe .. go to prev page
        else if ((e2.getX() - e1.getX()  > 40 && Math.abs(velocityX) > 100)) {
            //do your stuff
        	Log.v("left to right");
        	if(DetailActivity._currentPage >= 1)
        	{
        		DetailActivity._currentPage -- ;
        		Log.v("_activity._currentPage: " +DetailActivity._currentPage);
        		Log.v(" _activity._screenHeight:"  + DetailActivity._screenHeight);
        	
            	//int scrollTo = _activity._currentPage * _activity._screenHeight;
            	//Log.v("scrollTo:" + scrollTo);
        		String scrollTo  = "var page = $('.page').eq("+ (DetailActivity._currentPage) +").position().top;$('html, body').stop().animate({scrollTop: page}, 300);";
            	WebviewDetail.this.loadUrl("javascript:"+scrollTo);
            	return true;
        	}
        	
        }
		
		
		
		// TODO Auto-generated method stub
		//return super.onFling(e1, e2, velocityX, velocityY);
		return true;
	}

	/* (non-Javadoc)
	 * @see android.view.GestureDetector.SimpleOnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float)
	 */
	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		Log.v("onSCroll");
			return true;
		
	}
  }		
}
